package org.example.config;

import cn.hutool.setting.Setting;
import com.alibaba.druid.pool.DruidDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.*;

import javax.sql.DataSource;

@Configuration
@ConditionalOnClass(com.alibaba.druid.pool.DruidDataSource.class)
@EnableConfigurationProperties()
@PropertySource(value = {"classpath:druid.properties"})
@ConditionalOnProperty(name = "spring.datasource.type", havingValue = "com.alibaba.druid.pool.DruidDataSource", matchIfMissing = true)
public class DruidDataSourceConfig {

    private static final Logger LOGGER = LoggerFactory.getLogger(DruidDataSourceConfig.class);

    @Bean(name="dataSource")     //声明其为Bean实例
    @Primary  //在同样的DataSource中，首先使用被标注的DataSource
    @ConfigurationProperties(prefix = "spring.datasource.druid")
    public DataSource dataSource() {
        Setting settings = new Setting("db.ini");
        String url = settings.getByGroup("url", "");
        String driver = settings.getByGroup("driver", "");
        String username = settings.getByGroup("username", "");
        String password = settings.getByGroup("password", "");
        DruidDataSource datasource = new DruidDataSource();
        datasource.setUrl(url);
        datasource.setUsername(username);
        datasource.setPassword(password);
        datasource.setDriverClassName(driver);
        LOGGER.info("init datasource url={},username={}",url,username);
        return datasource;
    }
}